package com.yld.demo.controller;


import com.alibaba.fastjson.JSON;
import com.yld.demo.entity.UserInfo;
import com.yld.demo.service.UserInfoService;
import com.yld.demo.util.kafka.KafkaData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.*;
import yld.utils.ResultUtils;
import yld.utils.ResultVo;

import java.util.List;


@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    KafkaTemplate<String, String> kafka;

    //列表
    @GetMapping("/selectAll")
    public ResultVo list() {
        List<UserInfo> userInfos = userInfoService.selectAllLimit(10);
        return ResultUtils.success("查询成功", userInfos);
    }

    @GetMapping("/selectById/{id}")
    public ResultVo selectById(@PathVariable Integer id) throws InterruptedException {
        UserInfo userInfo = userInfoService.selectById(id);
        return ResultUtils.success("查询成功", userInfo);
    }

    //增加
    @PostMapping("/add")
    public ResultVo AddUserInfo(@RequestBody UserInfo userInfo) {
        KafkaData kafkaData = new KafkaData();
        kafkaData.setType("user_add");
        kafkaData.setData(JSON.toJSONString(userInfo));
        kafka.send("test", JSON.toJSONString(kafkaData));
        return ResultUtils.success("新增成功");
    }

    @PutMapping("/edit")
    public ResultVo edit(@RequestBody UserInfo userinfo) {
        if (userInfoService.updateById(userinfo)) {
            return ResultUtils.success("编辑成功");
        }
        return ResultUtils.error("编辑失败!");
    }

    @DeleteMapping("/{userId}")
    public ResultVo delete(@PathVariable("userId") Long userId) {
        if (userInfoService.removeById(userId)) {
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.error("删除失败!");
    }
}

